﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Text.RegularExpressions;
using System.IO;

namespace ajayumi.develop.win32.Transport.AppUpgrade
{
    /// <summary>
    /// 参数序列化类
    /// Author   : 黄乙冬
    /// Date     : 2011-9-1 08:35:15
    /// </summary>
    /// <remarks>
    /// iscfmchkver="0" isfull="0" issilent="0" appname="ETM" appdirectory="C:\Temp\ETM" processname="Perlove.ETM.WinForm.UI" appversion="1.0.0.0"
    /// iscfmchkver="1" isfull="1" issilent="0" appname="TestApp" appdirectory="E:\Temp\TestApp" processname="TestApp" appversion="1.0.0.0"
    /// </remarks>
    internal static class ArgumentSerialization
    {
        #region Properties

        /// <summary>
        /// 是否需要确认检测版本
        /// </summary>
        internal static bool IsConfirmCheckVersion { get; set; }

        /// <summary>
        /// 是否进行完整升级
        /// </summary>
        internal static bool IsFullUpgrade { get; set; }

        /// <summary>
        /// 是否为后台模式升级
        /// </summary>
        internal static bool IsSilent { get; set; }

        /// <summary>
        /// 待升级的应用程序名称，通过应用程序名称从服务器得到更新信息
        /// </summary>
        internal static string AppName { get; set; }

        /// <summary>
        /// 待升级的应用程序所在目录路径
        /// </summary>
        internal static string AppDirectory { get; set; }

        /// <summary>
        /// 待升级的应用程序进程名称
        /// </summary>
        internal static string ProcessName { get; set; }

        /// <summary>
        /// 待升级的应用程序当前版本
        /// </summary>
        internal static string AppVersion { get; set; }

        /// <summary>
        /// 应用程序最新版本号
        /// </summary>
        internal static string AppLatestVersion { get; set; }

        #endregion

        /// <summary>
        /// 加载默认的参数
        /// </summary>
        private static void LoadFromConfig()
        {
            //是否询问检测版本
            string isCfmChkVer = ConfigurationManager.AppSettings["IsConfirmCheckVersion"];
            if (!string.IsNullOrEmpty(isCfmChkVer) && isCfmChkVer.Equals("1"))
            { IsConfirmCheckVersion = true; }
            else
            { IsConfirmCheckVersion = false; }

            //是否完整升级
            string isFull = ConfigurationManager.AppSettings["IsFullUpgrade"];
            if (!string.IsNullOrEmpty(isFull) && isFull.Equals("1"))
            { IsFullUpgrade = true; }
            else
            { IsFullUpgrade = false; }

            //是否后台升级
            string isSilent = ConfigurationManager.AppSettings["IsSilent"];
            if (!string.IsNullOrEmpty(isSilent) && isSilent.Equals("1"))
            { IsSilent = true; }
            else
            { IsSilent = false; }

            //应用程序名称
            AppName = ConfigurationManager.AppSettings["AppName"];
            //if (string.IsNullOrEmpty(AppName))
            //{ throw new NotSupportedException("必须指定待升级的应用程序名称"); }

            //应用程序路径
            AppDirectory = ConfigurationManager.AppSettings["AppDirectory"];
            if (string.IsNullOrEmpty(AppDirectory))
            { AppDirectory = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\'); }

            //应用程序的进程名称
            ProcessName = ConfigurationManager.AppSettings["ProcessName"];
            //if (string.IsNullOrEmpty(AppName))
            //{ throw new NotSupportedException("必须指定待升级的应用程序的进程名称"); }

            AppVersion = ConfigurationManager.AppSettings["AppVersion"];
            if (string.IsNullOrEmpty(AppVersion))
            { AppVersion = "0.0.0.0"; }
        }

        internal static void Load(string[] args)
        {
            LoadFromConfig();
            if (args == null || args.Length <= 0)
            {
                return;
            }

            foreach (string item in args)
            {
                Match match = Regex.Match(item, "(?<key>.*)=\"?(?<value>.*[^\"])", RegexOptions.IgnoreCase);
                if (match.Success && match.Groups["key"].Value.Equals("iscfmchkver", StringComparison.InvariantCultureIgnoreCase))
                {
                    string value = match.Groups["value"].Value;
                    IsConfirmCheckVersion = value.Equals("1");
                }
                else if (match.Success && match.Groups["key"].Value.Equals("isfull", StringComparison.InvariantCultureIgnoreCase))
                {
                    string value = match.Groups["value"].Value;
                    IsFullUpgrade = value.Equals("1");
                }
                else if (match.Success && match.Groups["key"].Value.Equals("issilent", StringComparison.InvariantCultureIgnoreCase))
                {
                    string value = match.Groups["value"].Value;
                    IsSilent = value.Equals("1");
                }
                else if (match.Success && match.Groups["key"].Value.Equals("appname", StringComparison.InvariantCultureIgnoreCase))
                {
                    AppName = match.Groups["value"].Value;
                }
                else if (match.Success && match.Groups["key"].Value.Equals("appdirectory", StringComparison.InvariantCultureIgnoreCase))
                {
                    AppDirectory = match.Groups["value"].Value;
                    if (string.IsNullOrEmpty(AppDirectory))
                    { AppDirectory = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\'); }
                }
                else if (match.Success && match.Groups["key"].Value.Equals("processname", StringComparison.InvariantCultureIgnoreCase))
                {
                    ProcessName = match.Groups["value"].Value;
                }
                else if (match.Success && match.Groups["key"].Value.Equals("appversion", StringComparison.InvariantCultureIgnoreCase))
                {
                    AppVersion = match.Groups["value"].Value;
                    if (string.IsNullOrEmpty(AppVersion))
                    { AppVersion = "0.0.0.0"; }
                }
            }
        }

        internal static void Save()
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");
            appSettings.Settings.Remove("AppVersion");
            appSettings.Settings.Add("AppVersion", AppLatestVersion);
            config.Save();
        }

    }
}
